package com.bianxingji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bianxingji.mapper.BxjMediaFilesMapper;
import com.bianxingji.model.PageParams;
import com.bianxingji.model.PageResult;
import com.bianxingji.model.RestResponse;
import com.bianxingji.model.dto.QueryMediaParamsDto;
import com.bianxingji.po.BxjMediaFiles;
import com.bianxingji.service.BxjMediaFileService;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description TODO
 * @author Mr.M
 * @date 2022/9/10 8:58
 * @version 1.0
 */
@Slf4j
@Service
@DubboService
public class BxjMediaFileServiceImpl implements BxjMediaFileService {

  @Autowired
  BxjMediaFilesMapper bxjMediaFilesMapper;

  @Autowired
  private MinioClient minioClient;


 //存储普通文件
 @Value("${minio.bucket.files}")
 private String bucket_mediafiles;
 @Value("${minio.bucket.img}")
 private String bucket_img_mediafiles;
 @Value("${minio.endpoint}")
 private String endpoint;



 @Override
 public PageResult<BxjMediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {
  //构建查询条件对象
  LambdaQueryWrapper<BxjMediaFiles> queryWrapper = new LambdaQueryWrapper<>();
  //分页对象
  Page<BxjMediaFiles> page = new Page<>(pageParams.getCurrentPage(), pageParams.getPageSize());
  // 查询数据内容获得结果
  Page<BxjMediaFiles> pageResult = bxjMediaFilesMapper.selectPage(page, queryWrapper);
  // 获取数据列表
  List<BxjMediaFiles> list = pageResult.getRecords();
  // 获取数据总数
  long total = pageResult.getTotal();
  // 构建结果集
  PageResult<BxjMediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getCurrentPage(), pageParams.getPageSize());
  return mediaListResult;

 }

 @Override
 public BxjMediaFiles uploadAvatar(byte[] file,String fileType){
  // 确保 fileType 不为空，并且将其转换为小写字母
  if (fileType == null || fileType.isEmpty()) {
   throw new IllegalArgumentException("File type cannot be null or empty");
  }
  // 临时文件前缀
  String tempFilePrefix = "avatar_";
  // 创建一个临时文件，使用默认的临时目录
     File tempFile = null;
     try {
         tempFile = File.createTempFile(tempFilePrefix, "." + fileType);
     } catch (IOException e) {
         throw new RuntimeException(e);
     }
     // 确保文件在应用程序结束时被删除
  tempFile.deleteOnExit();

  // 将字节数组写入临时文件
  try (FileOutputStream fileOut = new FileOutputStream(tempFile)) {
   fileOut.write(file);  // 写入字节数组
   String extension = tempFile.getName().substring(tempFile.getName().lastIndexOf("."));
   String mimeType = getMimeType(extension);
   String fileMd5 = getFileMd5(tempFile);
   String defaultFolderPath = getImgtFolderPath(fileMd5);
   addMediaFilesToMinIO(tempFile.getAbsolutePath(),mimeType,bucket_mediafiles,defaultFolderPath+fileMd5+extension);
  } catch (Exception e) {
      throw new RuntimeException(e);
  } finally {
   // 确保在操作完成后删除临时文件
   if (tempFile != null && tempFile.exists()) {
    boolean deleted = tempFile.delete();
    if (!deleted) {
     log.error("Failed to delete temporary file: " + tempFile.getAbsolutePath());
    }
   }
  }


  return null;
 }

 @Override
 public String getUrlById(String id) {
  BxjMediaFiles bxjMediaFiles = bxjMediaFilesMapper.selectById(id);
  return  !Objects.isNull(bxjMediaFiles) ? endpoint+"/"+bucket_mediafiles+"/"+bxjMediaFiles.getUrl():"";
 }

 @Override
 public RestResponse<Boolean> checkFile(String fileMd5) {
  //先查询数据库
  BxjMediaFiles mediaFiles = bxjMediaFilesMapper.selectById(fileMd5);
  if(mediaFiles!=null){
   //桶
   String bucket = mediaFiles.getBucket();
   //objectname
   String filePath = mediaFiles.getFilePath();
   //如果数据库存在再查询 minio
   GetObjectArgs getObjectArgs = GetObjectArgs.builder()
           .bucket(bucket)
           .object(filePath)
           .build();
   //查询远程服务获取到一个流对象
   try {
    FilterInputStream inputStream = minioClient.getObject(getObjectArgs);
    if(inputStream!=null){
     //文件已存在
     return RestResponse.success(true);
    }
   } catch (Exception e) {
    e.printStackTrace();
   }

  }

  //文件不存在
  return RestResponse.success(false);
 }

 @Override
 public RestResponse<Boolean> checkChunk(String fileMd5, int chunk) {
  //根据md5得到分块文件所在目录的路径
  String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);

  //如果数据库存在再查询 minio
  GetObjectArgs getObjectArgs = GetObjectArgs.builder()
          .bucket(bucket_mediafiles)
          .object(chunkFileFolderPath+chunk)
          .build();
  //查询远程服务获取到一个流对象
  try {
   FilterInputStream inputStream = minioClient.getObject(getObjectArgs);
   if(inputStream!=null){
    //文件已存在
    return RestResponse.success(true);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

  //文件不存在
  return RestResponse.success(false);
 }

 @Override
 public RestResponse uploadChunk(String fileMd5, int chunk, String localFilePath) {
  //分块文件的路径
  String chunkFilePath = getChunkFileFolderPath(fileMd5) + chunk;
  //获取mimeType
  String mimeType = getMimeType(null);
  //将分块文件上传到minio
  boolean b = addMediaFilesToMinIO(localFilePath, mimeType, bucket_mediafiles, chunkFilePath);
  if(!b){
   return RestResponse.validfail(false,"上传分块文件失败");
  }
  //上传成功
  //入库 在合并文件中入库
  // TODO 上传分块后就进行合并文件，但是最好还是丢在消息队列中去
  return RestResponse.success(true);
 }

 @Override
 public RestResponse uploadImg(MultipartFile file) {
  // 获取文件的原始文件名
  String fileName = file.getOriginalFilename();
  // 创建临时文件
  File tempFile = new File(System.getProperty("java.io.tmpdir") + "/" + fileName);
  try {
   file.transferTo(tempFile);
   String extension = tempFile.getName().substring(tempFile.getName().lastIndexOf("."));
   String mimeType = getMimeType(extension);
   String fileMd5 = getFileMd5(tempFile);
   String defaultFolderPath = getImgtFolderPath(fileMd5);
   addMediaFilesToMinIO(tempFile.getAbsolutePath(),mimeType,bucket_img_mediafiles,defaultFolderPath+fileMd5+extension);
   /*
    * 将媒资信息入库
    * */
   BxjMediaFiles bxjMediaFiles = new BxjMediaFiles();
   bxjMediaFiles.setBucket(bucket_img_mediafiles);
   bxjMediaFiles.setFilename(fileName);
   bxjMediaFiles.setId(fileMd5);
   bxjMediaFiles.setFilePath(defaultFolderPath+fileMd5+extension);
   bxjMediaFiles.setUrl(defaultFolderPath+fileMd5+extension);
   bxjMediaFiles.setFileId(fileMd5);
   bxjMediaFilesMapper.insert(bxjMediaFiles);
  } catch (IOException e) {
   log.error(e.getMessage());
  } finally {
//    确保在操作完成后删除临时文件
   if (tempFile != null && tempFile.exists()) {
    boolean deleted = tempFile.delete();
    if (!deleted) {
     log.error("Failed to delete temporary file: " + tempFile.getAbsolutePath());
    }
   }
   return null;
  }
 }

 @Override
 public RestResponse mergechunks(String fileMd5, int chunkTotal, BxjMediaFiles bxjMediaFiles) {
  //分块文件所在目录
  String chunkFileFolderPath = getChunkFileFolderPath(fileMd5);
  //找到所有的分块文件
  List<ComposeSource> sources = Stream.iterate(0, i -> ++i).limit(chunkTotal).map(
          i -> ComposeSource.builder().bucket(bucket_mediafiles).object(chunkFileFolderPath + i).build()).collect(Collectors.toList());
  //源文件名称
  String filename = bxjMediaFiles.getFilename();
  //扩展名
  String extension = filename.substring(filename.lastIndexOf("."));
  //合并后文件的objectname
  String objectName = getFilePathByMd5(fileMd5, extension);
  //指定合并后的objectName等信息
     ComposeObjectArgs composeObjectArgs = ComposeObjectArgs.builder()
          .bucket(bucket_mediafiles)
          .object(objectName)//合并后的文件的objectname
          .sources(sources)//指定源文件
          .build();
  //===========合并文件============
  //报错size 1048576 must be greater than 5242880，minio默认的分块文件大小为5M
  try {
   minioClient.composeObject(composeObjectArgs);
  } catch (Exception e) {
   e.printStackTrace();
   log.error("合并文件出错,bucket:{},objectName:{},错误信息:{}",bxjMediaFiles,objectName,e.getMessage());
   return RestResponse.validfail(false,"合并文件异常");
  }

  //===========校验合并后的和源文件是否一致，视频上传才成功===========
  //先下载合并后的文件
  File file = downloadFileFromMinIO(bucket_mediafiles, objectName);
  try(FileInputStream fileInputStream = new FileInputStream(file)){
   //计算合并后文件的md5
   String mergeFile_md5 = DigestUtils.md5Hex(fileInputStream);
   //比较原始md5和合并后文件的md5
   if(!fileMd5.equals(mergeFile_md5)){
    log.error("校验合并文件md5值不一致,原始文件:{},合并文件:{}",fileMd5,mergeFile_md5);
    return RestResponse.validfail(false,"文件校验失败");
   }
   //文件大小
   bxjMediaFiles.setFileSize(file.length());
  }catch (Exception e) {
   return RestResponse.validfail(false,"文件校验失败");
  }

  //==============将文件信息入库============
  BxjMediaFiles mediaFiles = new BxjMediaFiles();
  BeanUtils.copyProperties(bxjMediaFiles,mediaFiles);
  mediaFiles.setId(fileMd5);
  mediaFiles.setFileId(fileMd5);
  mediaFiles.setBucket(bucket_mediafiles);
  //file_path
  mediaFiles.setFilePath(objectName);
  mediaFiles.setUrl(objectName);
  if(bxjMediaFilesMapper.insert(mediaFiles)<=0){
   return RestResponse.validfail(false,"文件入库失败");
 }
  //==========清理分块文件=========;
  clearChunkFiles(chunkFileFolderPath,chunkTotal);
  file.delete();
  return RestResponse.success(true);
 }

 @Override
 public File downloadFileFromMinIO(String bucket, String objectName) {
  //临时文件
  File minioFile = null;
  FileOutputStream outputStream = null;
  try{
   InputStream stream = minioClient.getObject(GetObjectArgs.builder()
           .bucket(bucket)
           .object(objectName)
           .build());
   //创建临时文件
   minioFile=File.createTempFile("minio", ".merge");
   outputStream = new FileOutputStream(minioFile);
   IOUtils.copy(stream,outputStream);
   return minioFile;
  } catch (Exception e) {
   e.printStackTrace();
  }finally {
   if(outputStream!=null){
    try {

     outputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
  return null;
 }

 /**
  * 将文件上传到minio
  * @param localFilePath 文件本地路径
  * @param mimeType 媒体类型
  * @param bucket 桶
  * @param objectName 对象名
  * @return
  */
 public boolean addMediaFilesToMinIO(String localFilePath,String mimeType,String bucket, String objectName){
  try {
   UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
           .bucket(bucket)//桶
           .filename(localFilePath) //指定本地文件路径
           .object(objectName)//对象名 放在子目录下
           .contentType(mimeType)//设置媒体文件类型
           .build();
   //上传文件
   minioClient.uploadObject(uploadObjectArgs);
   log.debug("上传文件到minio成功,bucket:{},objectName:{},错误信息:{}",bucket,objectName);
   return true;
  } catch (Exception e) {
   e.printStackTrace();
   log.error("上传文件出错,bucket:{},objectName:{},错误信息:{}",bucket,objectName,e.getMessage());
  }
  return false;
 }

 //获取图片文件的上传地址
 private String getImgtFolderPath(String fileMd5) {
  return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" ;
 }
 //获取文件的md5
 private String getFileMd5(File file) {
  try (FileInputStream fileInputStream = new FileInputStream(file)) {
   String fileMd5 = DigestUtils.md5Hex(fileInputStream);
   return fileMd5;
  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
 }
 //根据扩展名获取mimeType
 private String getMimeType(String extension){
  if(extension == null){
   extension = "";
  }
  //根据扩展名取出mimeType
  ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
  String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;//通用mimeType，字节流
  if(extensionMatch!=null){
   mimeType = extensionMatch.getMimeType();
  }
  return mimeType;
 }
 //得到分块文件的目录
 private String getChunkFileFolderPath(String fileMd5) {
  return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + "chunk" + "/";
 }
 /**
  * 得到合并后的文件的地址
  * @param fileMd5 文件id即md5值
  * @param fileExt 文件扩展名
  * @return
  */
 private String getFilePathByMd5(String fileMd5,String fileExt){
  return   fileMd5.substring(0,1) + "/" + fileMd5.substring(1,2) + "/" + fileMd5 + "/" +fileMd5 +fileExt;
 }
 /**
  * 清除分块文件
  * @param chunkFileFolderPath 分块文件路径
  * @param chunkTotal 分块文件总数
  */
 private void clearChunkFiles(String chunkFileFolderPath,int chunkTotal){
  Iterable<DeleteObject> objects =  Stream.iterate(0, i -> ++i).limit(chunkTotal).map(i -> new DeleteObject(chunkFileFolderPath+ i)).collect(Collectors.toList());;
  RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket(bucket_mediafiles).objects(objects).build();
  Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
  //要想真正删除
  results.forEach(f->{
   try {
    DeleteError deleteError = f.get();
   } catch (Exception e) {
    e.printStackTrace();
   }
  });

 }
}
